package com.itheima.behavior.server.impl;

import com.heima.model.common.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UnLikesBehaviorDTO;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.common.user.pojo.ApUser;
import com.itheima.behavior.server.ApBehaviorEntryService;
import com.itheima.behavior.server.ApUnlikeBehaviorService;
import com.itheima.common.exception.CustException;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        //根据当前登录用户id查询行为实体对象查询 若不存在 则增加一个

        ApBehaviorEntry entry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId)), ApBehaviorEntry.class);
        if (entry==null){
            entry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        }
        //如果是不喜欢操作判断是否已经点了
        if (dto.getType()==0){//不喜欢
            ApUnlikesBehavior one = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(entry.getId()).and("articleId").is(dto.getArticleId())), ApUnlikesBehavior.class);
            if (one==null){
                ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setCreatedTime(new Date());
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setType(ApUnlikesBehavior.Type.UNLIKE.getCode());
                apUnlikesBehavior.setEntryId(entry.getId());

                ApUnlikesBehavior save = mongoTemplate.save(apUnlikesBehavior);
                return ResponseResult.okResult();
            }
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"不能重复点不喜欢");
        }
        //取消不喜欢
        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(entry.getId()).and("articleId").is(dto.getArticleId())),ApUnlikesBehavior.class);
        return ResponseResult.okResult();



    }
}
